package com.xplay.xpocker.config.security;


import com.xplay.xpocker.util.JwtUtils;
import com.xplay.xpocker.util.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
    UserDetailsService userDetailsService;

    RedisUtil redisUtil;

    public JwtAuthorizationTokenFilter(UserDetailsService userDetailsService, RedisUtil redisUtil) {
        this.userDetailsService = userDetailsService;
        this.redisUtil = redisUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authToken = request.getHeader("Authory");
        String username = null;
        try {
            if (JwtUtils.validateToken(authToken)) {
                Claims claims = JwtUtils.getAllClaimsFromToken(authToken);
                username = claims.getId();
            }
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                String token = redisUtil.get("USER_LOGIN:" + username);
                if (token != null && !token.equals(authToken)) {
                    chain.doFilter(request, response);
                    return;
                }
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        chain.doFilter(request, response);
    }
}
